package com.tts.service;

import com.tts.entity.SystemLog;
import com.tts.entity.User;
import com.tts.repository.SystemLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class LogService {

    @Autowired
    private SystemLogRepository systemLogRepository;

    public void createLog(User user, String operation, String description, String ipAddress) {
        SystemLog log = new SystemLog();
        log.setUser(user);
        log.setOperation(operation);
        log.setDescription(description);
        log.setIpAddress(ipAddress);
        log.setCreatedTime(LocalDateTime.now());
        systemLogRepository.save(log);
    }

    public Page<SystemLog> getLogs(String keyword, String operation, String startDate, String endDate, Pageable pageable) {
        Specification<SystemLog> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (keyword != null && !keyword.isEmpty()) {
                predicates.add(cb.or(
                    cb.like(root.get("user").get("username"), "%" + keyword + "%"),
                    cb.like(root.get("description"), "%" + keyword + "%")
                ));
            }

            if (operation != null && !operation.isEmpty()) {
                predicates.add(cb.equal(root.get("operation"), operation));
            }

            if (startDate != null && !startDate.isEmpty()) {
                LocalDateTime start = LocalDate.parse(startDate).atStartOfDay();
                predicates.add(cb.greaterThanOrEqualTo(root.get("createdTime"), start));
            }

            if (endDate != null && !endDate.isEmpty()) {
                LocalDateTime end = LocalDate.parse(endDate).atTime(LocalTime.MAX);
                predicates.add(cb.lessThanOrEqualTo(root.get("createdTime"), end));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };

        return systemLogRepository.findAll(spec, pageable);
    }
} 